package mirrormonkey.core.client;

import java.util.ArrayList;
import java.util.Collection;

import mirrormonkey.core.messages.EntityChangeMessage;
import mirrormonkey.core.messages.EntityEndMessage;
import mirrormonkey.core.messages.EntityInitMessage;
import mirrormonkey.core.module.CoreModule;
import mirrormonkey.framework.ClientSyncAppState;
import mirrormonkey.framework.ConnectionInfo;

import com.jme3.network.MessageConnection;

public class ClientCoreModule extends CoreModule {

	protected final EntityInitListener initListener;

	protected final EntityEndListener endListener;

	protected final EntityChangeListener changeListener;

	protected final ClientConnectionInfo connectionInfo;

	protected final Collection<ConnectionInfo> connectionInfoAsCollection;

	public ClientCoreModule(ClientSyncAppState appState) {
		super(appState);

		initListener = new EntityInitListener(this);
		appState.eventManager.addMessageListener(initListener,
				EntityInitMessage.class);

		endListener = new EntityEndListener(appState.entityProvider, this);
		appState.eventManager.addMessageListener(endListener,
				EntityEndMessage.class);

		changeListener = new EntityChangeListener(appState.entityProvider, this);
		appState.eventManager.addMessageListener(changeListener,
				EntityChangeMessage.class);

		connectionInfo = new ClientConnectionInfo(appState, appState.client);

		connectionInfoAsCollection = new ArrayList<ConnectionInfo>(1);
		connectionInfoAsCollection.add(connectionInfo);
	}

	@Override
	public void update(float tpf) {
		super.update(tpf);
		connectionInfo.update(tpf);
	}

	@Override
	public ClientConnectionInfo getData(MessageConnection forConnection) {
		return connectionInfo.getConnection().equals(forConnection) ? connectionInfo
				: null;
	}

	public Collection<ConnectionInfo> getConnectionInfoAsCollection() {
		return connectionInfoAsCollection;
	}

	public ClientEntityData getData(int id) {
		ClientEntityData data = (ClientEntityData) appState.entityProvider
				.getData(id);
		if (data != null) {
			return data;
		}
		return new ClientEntityData(id, null, this);
	}

}
